package nc.bs.bd.pfxx.plugin;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Logger;
import nc.bs.pfxx.ISwapContext;
import nc.bs.pfxx.plugin.AbstractPfxxPlugin;
import nc.itf.bd.material.assign.IMaterialAssignService;
import nc.itf.bd.material.baseinfo.IMaterialBaseInfoService;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.bd.errorlog.ErrLogReturnValue;
import nc.vo.bd.errorlog.ErrorMsgVO;
import nc.vo.bd.material.MaterialConvertVO;
import nc.vo.bd.material.MaterialTaxTypeVO;
import nc.vo.bd.material.MaterialVO;
import nc.vo.corg.CostRegionVO;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pfxx.auxiliary.AggxsysregisterVO;
import nc.vo.pfxx.util.PfxxPluginUtils;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFBoolean;
import nccloud.commons.lang.StringUtils;

public class MaterialPfxxPlugin extends AbstractPfxxPlugin {
    private BaseDAO baseDAO = null;

    private IMaterialBaseInfoService service = null;

    protected Object processBill(Object vo, ISwapContext swapContext, AggxsysregisterVO aggxsysvo) throws BusinessException {
        String pk = null;
        try {
            MaterialVO materialVO = (MaterialVO) vo;
            pk = PfxxPluginUtils.queryBillPKBeforeSaveOrUpdate(swapContext.getBilltype(), swapContext.getDocID());
            if (StringUtils.isBlank(pk)) {
                materialVO = insertMaterialVO(materialVO);
                PfxxPluginUtils.addDocIDVsPKContrast(swapContext.getBilltype(), swapContext.getDocID(), materialVO.getPrimaryKey());
                return materialVO.getPrimaryKey();
            }
            getService().updateMaterial(getUpdateVO(materialVO, pk));
        } catch (Exception ex) {
            Logger.error(ex.getMessage(), ex.getCause());
            throw new BusinessException(ex.getMessage(), ex.getCause());
        }
        return pk;
    }

    private BaseDAO getBaseDAO() {
        if (this.baseDAO == null) {
            this.baseDAO = new BaseDAO();
        }
        return this.baseDAO;
    }

    private MaterialVO getInsertVO(MaterialVO materialVO) throws DAOException {
        materialVO.setEnablestate(Integer.valueOf(2));
        materialVO.setStatus(2);
        materialVO.setMaterialconvert(getMaterialConvertVOs(materialVO));
        materialVO.setMaterialtaxtype(getMaterialTaxTypeVOs(materialVO));
        return materialVO;
    }


    private MaterialConvertVO[] getMaterialConvertVOs(MaterialVO MaterialVO) throws DAOException {
        List<MaterialConvertVO> newConverts = new ArrayList<MaterialConvertVO>();
        if (StringUtils.isNotBlank(MaterialVO.getPrimaryKey())) {
            Collection<MaterialConvertVO> oldAgentStores = getBaseDAO().retrieveByClause(MaterialConvertVO.class, "pk_material = '" + MaterialVO.getPrimaryKey() + "'", new String[]{"pk_materialconvert"});

            for (MaterialConvertVO agentstore : oldAgentStores) {
                agentstore.setStatus(3);
                newConverts.add(agentstore);
            }
        }
        if (MaterialVO.getMaterialconvert() != null) {
            MaterialVO.getMaterialconvert();/*  87 */
            for (MaterialConvertVO agentstore : MaterialVO.getMaterialconvert()) {

                agentstore.setStatus(2);

                newConverts.add(agentstore);

            }

        }
        return newConverts.toArray(new MaterialConvertVO[0]);
    }

    private MaterialTaxTypeVO[] getMaterialTaxTypeVOs(MaterialVO MaterialVO) throws DAOException {
        List<MaterialTaxTypeVO> newConverts = new ArrayList<MaterialTaxTypeVO>();
        if (StringUtils.isNotBlank(MaterialVO.getPrimaryKey())) {
            Collection<MaterialTaxTypeVO> oldAgentStores = getBaseDAO().retrieveByClause(MaterialTaxTypeVO.class, "pk_material = '" + MaterialVO.getPrimaryKey() + "'", new String[]{"pk_materialtaxtype"});

            for (MaterialTaxTypeVO agentstore : oldAgentStores) {
                agentstore.setStatus(3);
                newConverts.add(agentstore);
            }
        }
        if (MaterialVO.getMaterialtaxtype() != null) {
            MaterialVO.getMaterialtaxtype();
            for (MaterialTaxTypeVO agentstore : MaterialVO.getMaterialtaxtype()) {

                agentstore.setStatus(2);

                newConverts.add(agentstore);

            }

        }
        return newConverts.toArray(new MaterialTaxTypeVO[0]);
    }

    private IMaterialBaseInfoService getService() {
        if (this.service == null) {
            this.service = NCLocator.getInstance().lookup(IMaterialBaseInfoService.class);
        }
        return this.service;
    }

    private MaterialVO getUpdateVO(MaterialVO materialVO, String pk) throws BusinessException {
        MaterialVO oldVO = (MaterialVO) getBaseDAO().retrieveByPK(MaterialVO.class, pk, new String[]{"creator", "creationtime", "pk_source", "version", "latest", "enablestate"});


        if (oldVO == null) {
            throw new BusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("bdpub", "0bdpub0057"));
        }
        //默认数据处理 zb 2024-10-24
        dealFinalParam(materialVO);

        materialVO.setPrimaryKey(pk);
        materialVO.setCreator(oldVO.getCreator());
        materialVO.setCreationtime(oldVO.getCreationtime());
        materialVO.setPk_source(oldVO.getPk_source());
        materialVO.setVersion(oldVO.getVersion());
        materialVO.setLatest(oldVO.getLatest());
        materialVO.setEnablestate(oldVO.getEnablestate());
        materialVO.setStatus(1);
        materialVO.setTs(oldVO.getTs());
        materialVO.setMaterialconvert(getMaterialConvertVOs(materialVO));
        materialVO.setMaterialtaxtype(getMaterialTaxTypeVOs(materialVO));
        return materialVO;
    }

    private MaterialVO insertMaterialVO(MaterialVO materialVO) throws BusinessException {

        //默认数据处理 zb 2024-10-24
        dealFinalParam(materialVO);

        if (StringUtils.isBlank(materialVO.getPk_source())) {
            materialVO = getService().insertMaterial(getInsertVO(materialVO));
        } else {
            ErrLogReturnValue value = getService().createMaterialVersion(materialVO, materialVO.getPk_source());
            if (value.getReturnValue() == null || !value.getReturnValue().getClass().isArray()) {
                return materialVO;
            }
            materialVO = (MaterialVO) ((Object[]) value.getReturnValue())[0];
            LogErrorMessage(value);
        }

        /**
         * 	分配物料到成本域00101 zb 2024-10-24
         */
        //查询分配的成本域主键，默认分配 00101 安吉 0010101
        String orgSQL = "select code from org_orgs where dr = 0 and pk_org = '"+materialVO.getPk_org()+"'";
        Object orgcode = this.getBaseDAO().executeQuery(orgSQL, new ColumnProcessor());
        Collection<CostRegionVO> costRegionVOs = getBaseDAO().retrieveByClause(CostRegionVO.class, "code = '"+orgcode+"'");
        if (costRegionVOs.isEmpty()){
            throw new BusinessException("请到 财务成本域节点维护 成本域 ");
        }
        CostRegionVO CostRegionVO = (nc.vo.corg.CostRegionVO) costRegionVOs.toArray()[0];
//			  ErrLogReturnValue errLog =
        // 分配成本域
        IMaterialAssignService lookup = NCLocator.getInstance().lookup(IMaterialAssignService.class);

        lookup.assignMaterialByPks(new String[]{materialVO.getPk_material()}, new String[]{CostRegionVO.getPk_costregion()}, null);

        return materialVO;
    }

    private void LogErrorMessage(ErrLogReturnValue value) {
        ErrorMsgVO[] vos = value.getErrLogResult().getErrorMsgs();
        if (vos != null && vos.length > 0) {
            String message = NCLangRes4VoTransl.getNCLangRes().getStrByID("10140mag", "010140mag0200", null, new String[]{Integer.toString(value.getTotalNum()), Integer.toString(value.getErrLogResult().getErrorMessagegNum())}) + "\n";
            for (int i = 0; i < vos.length; i++) {
                message = message + vos[i].getErrormsg() + "\n";
            }
            Logger.debug(message);
        }
    }

    /**
     * 物料默认数据处理
     *
     * @param materialVO
     */
    private void dealFinalParam(MaterialVO materialVO) {
        // 默认数据处理
        materialVO.setEu_pdprice("2");
        materialVO.setFlag_drug(UFBoolean.FALSE);
        materialVO.setFlag_base(UFBoolean.FALSE);
        materialVO.setFlag_gmp(UFBoolean.FALSE);
        materialVO.setFlag_highrisk(UFBoolean.FALSE);
        materialVO.setFlag_iv(UFBoolean.FALSE);
        materialVO.setFlag_monitor(UFBoolean.FALSE);
        materialVO.setFlag_nuclide(UFBoolean.FALSE);
        materialVO.setFlag_onlycharge(UFBoolean.FALSE);
        materialVO.setFlag_province(UFBoolean.FALSE);
        materialVO.setFlag_quantitypu(UFBoolean.FALSE);
        materialVO.setFlag_reag(UFBoolean.FALSE);
        materialVO.setFlag_refrigeration(UFBoolean.FALSE);
        materialVO.setFlag_rm(UFBoolean.FALSE);
        materialVO.setFlag_rsa(UFBoolean.FALSE);
        materialVO.setFlag_sd(UFBoolean.FALSE);
        materialVO.setFlag_st(UFBoolean.FALSE);
        materialVO.setFlag_tend(UFBoolean.FALSE);
        materialVO.setFlag_tpn(UFBoolean.FALSE);
        materialVO.setFlag_vacc(UFBoolean.FALSE);
        materialVO.setDurable(UFBoolean.FALSE);
        materialVO.setElectronicsale(UFBoolean.FALSE);
        materialVO.setHcxt(UFBoolean.FALSE);
        materialVO.setHighvalue(UFBoolean.FALSE);
        materialVO.setInpurchase(UFBoolean.FALSE);
        materialVO.setImportstr(UFBoolean.FALSE);
        materialVO.setQualitymanflag(UFBoolean.FALSE);
        materialVO.setRetail(UFBoolean.FALSE);
        materialVO.setSerialmanaflag(UFBoolean.FALSE);
        materialVO.setSpecial(UFBoolean.FALSE);
        materialVO.setStoreback(UFBoolean.FALSE);
        materialVO.setWholemanaflag(UFBoolean.FALSE);
        materialVO.setIselectrans(UFBoolean.FALSE);
        materialVO.setIsprimarybarcode(UFBoolean.FALSE);
        materialVO.setIsfeature(UFBoolean.FALSE);
        materialVO.setIselectrans(UFBoolean.FALSE);
        materialVO.setCharge(UFBoolean.FALSE);
        materialVO.setProductfamily(UFBoolean.FALSE);
        if (materialVO.getMaterialconvert() != null) {
            materialVO.getMaterialconvert();
            for (MaterialConvertVO vo : materialVO.getMaterialconvert()) {
                vo.setFlag_ip(UFBoolean.FALSE);
                vo.setFlag_op(UFBoolean.FALSE);

            }
        }
    }
}
